package org.lgiavedoni.android.franq.service.sync;

import java.util.ArrayList;
import java.util.List;

import org.lgiavedoni.android.franq.core.service.Service;
import org.lgiavedoni.android.franq.core.sync.AbstractSyncProcess;
import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.util.implementation.ImplementationUtil;

public class SyncService extends Service {

	public static final SyncService inst = new SyncService();
	private final List<AbstractSyncProcess> syncs = new ArrayList<AbstractSyncProcess>();

	private SyncService() {

	}

	@Override
	public String getServiceName() {
		return "sync";
	}

	@Override
	protected void startInternal() {

	}

	@Override
	protected void stopInternal() {
		syncs.clear();
	}

	@Override
	public void _run() {

		for (Object obj : ImplementationUtil.getImplementationsInst(AbstractSyncProcess.class)) {
			syncs.add((AbstractSyncProcess) obj);
		}
	}

	public void exec() {
		for (AbstractSyncProcess sync : syncs) {
			try {
				sync.getClass().newInstance().sync();
			} catch (Exception ex) {
				Logger.inst.error(ex);
			}
		}
	}

	public void forceSync() {
		Logger.inst.info("Synchronization restarting procces --> STARTED");
		for (AbstractSyncProcess sync : syncs) {
			try {
				sync.getClass().newInstance().reset();
			} catch (Exception ex) {
				Logger.inst.error(ex);
			}
		}
		Logger.inst.info("Synchronization restarting procces --> FINISHED");
		exec();
	}

}
